`

PING 172.16.10.10 (172.16.10.10) 56(84) bytes of data.

64 bytes from 172.16.10.10: icmp_seq=1 ttl=64 time=0.024 ms

64 bytes from 172.16.10.10: icmp_seq=2 ttl=64 time=0.029 ms

64 bytes from 172.16.10.10: icmp_seq=3 ttl=64 time=0.029 ms

The ping command will run forever, so press CTRL+C to stop

its execution.

If you read pings manual page (by running man ping),

youll notice that there is no way to run it against multiple hosts at

once. But using bash, we can do this quite easily. The script in

Listing 4-7 pings all hosts on the network 172.16.10.0/24.

#!/bin/bash

FILE="${1}"

1 while read -r host; do

2 if ping -c 1 -W 1 -w 1 "${host}" &> /dev/null; then

echo "${host} is up."

fi

3 done < "${FILE}"

Listing 4-7

Pinging multiple hosts using a while loop

At 1, we run a while loop that reads from the file passed to the

script on the command line. This file is assigned to the variable

FILE. We read each line from the file and assign it to the host

variable. We then run the ping command using the -c argument

with a value of 1 at 2, which tells the ping command to send a

ping request only once and exit. By default on Linux, the ping

command sends ping requests indefinitely until you stop it manually

by sending a SIGHUP signal (CTRL+C).

We also use the arguments -W 1 (to set a timeout in seconds)

and -w 1 (to set a deadline in seconds) to limit how long ping will

wait to receive a response. This is important because we dont want

ping to get stuck on an unresponsive IP address; we want it to

continue reading from the file until all 254 hosts are tested.

Lastly, we use the standard input stream to read the file and

feed the while loop with its content 3.

Save this code to a file named multi_host_ping.sh and run it

while passing the hosts file. You should see that it picks up a few

live hosts:

$ ./multi_host_ping.sh 172-16-10-hosts.txt

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks